<?php

namespace App\Listeners;

use App\Events\OrderSubmitEvent;
use App\Forms\ConfigForms;
use App\Forms\GoodsAttributeForms;
use App\Forms\OrderForms;
use App\Forms\UserForms;
use App\Models\OrderDetail;
use App\Models\User;

class OrderDistributionListeners
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  OrderSubmitEvent  $event
     * @return void
     */
    public function handle(OrderSubmitEvent $event)
    {

        $order = $event->order;
        $user  = (new UserForms())->getUserDetail($order->uid);

        $parent = (new UserForms())->getUserDetail($user->pid);

        //判断是否为插件订单
        if (empty($order->source) && $user->pid && ($parent->level > User::L_DEFAULT) ) {

            $orderDetail = (new OrderForms())->orderDetailList($order->id);

            $total = 0;

            $percent = (new ConfigForms())->getDetail('commission_percent')->value;


            if ($user->level >= $parent->level) {
                foreach ($orderDetail as $item) {
                    /**
                     * @var OrderDetail $item
                     */
                    $total = bcadd($total, bcmul($item->goods_pay_price, bcmul($percent, 0.01, 2), 2), 2);
                }
            } else {
                $aForms = new GoodsAttributeForms();
                foreach ($orderDetail as $item) {
                    /**
                     * @var OrderDetail $item
                     */
                    //一顿不解释连招
                    $attribute    = $aForms->getGoodsAttributeDetail($item->attribute_id);
                    $userAmount   = User::LEVEL_GOODS_COMPARE[$user->level];
                    $parentAmount = User::LEVEL_GOODS_COMPARE[$parent->level];
                    $total        = bcadd($total, bcsub($attribute->$userAmount, $attribute->$parentAmount, 2), 2);

                }
            }

            $order->update([
                'pid' => $user->pid,
                'commission_amount' => $total,
            ]);

        }
        //
    }
}
